#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2022-04-28 13:47
# @Author  : 徐昌龙
# @FileName: dict_client.py
"""
dict 客户端： 与用户交互发起请求
"""
import sys
from socket import socket
import re


class DictHandle:
    @staticmethod
    def check(info):
        if re.findall("^\w{6,}$", info):
            return True
        return False

    def __init__(self, host="", port=0):
        self.host = host
        self.port = port
        self.address = (host, port)
        self.sock = self.__create_sock()

    def __create_sock(self):
        sock = socket()
        sock.connect(self.address)
        return sock

    def do_register(self, name, passwd):
        if DictHandle.check(name) and DictHandle.check(passwd):
            msg = f"R\t{name}\t{passwd}"
            self.sock.send(msg.encode())
            request = self.sock.recv(128).decode()
            if request == "T":
                print("注册成功")
                return True
            else:
                print("您的昵称太火爆了，请换一个昵称")
                return False
        else:
            print("名字或密码需为大于6位数字、字母、下划线")

    def do_login(self, name, passwd):
        msg = f"L\t{name}\t{passwd}"
        self.sock.send(msg.encode())
        request = self.sock.recv(128).decode()
        if request == "T":
            print("登录成功")
            return True
        else:
            print("您的昵称不存在，请重新输入")
            return False

    def do_exit(self):
        self.sock.send(b"E")
        self.sock.close()
        sys.exit("谢谢使用")

    def do_query(self, ):
        while True:
            word = input("请输入查询的单词：")
            if not word or word == "##":
                break
            msg = f"Q\t{word}"
            self.sock.send(msg.encode())
            response = self.sock.recv(1024 * 1024).decode()
            temp = response.split("\t", 1)
            if temp[0] == "T":
                print(f"单词：{word}\n意思：{temp[1]}")
            else:
                print("您输入的单词有误，请重新输入")

    def do_hist(self):
        self.sock.send(b"H")
        response = self.sock.recv(1024).decode()
        temp = response.split("\t")
        if temp[0] == "T":
            for row in temp[1].split("//", 4):
                row = row.split("##", 3)
                print(f"name:{row[0]}\n"
                      f"word:{row[1]}\n"
                      f"mean:{row[2]}\n"
                      f"time:{row[3]}\n")
        else:
            print("您还没有查询记录")


class DictView:
    def __init__(self, host="", port=9):
        self.host = host
        self.port = port
        self.address = (host, port)
        self.handle = DictHandle(host, port)

    def __menu_1(self):
        while True:
            print("""
            ============welcome=============
            1.注册        2.登录        3.退出
            """)
            item = input("请输入选项：")
            if item == "1":
                name = input("User:")
                passwd = input("Password:")
                if self.handle.do_register(name, passwd):
                    self.__menu_2()
            elif item == "2":
                name = input("User:")
                passwd = input("Password:")
                if self.handle.do_login(name, passwd):
                    self.__menu_2()
            elif item == "3":
                self.handle.do_exit()

            else:
                print("请输入正确选项")

    def __menu_2(self):
        while True:
            print("""
            ============welcome=============
            1.查单词        2.历史记录        3.注销
            """)
            item = input("请输入选项：")
            if item == "1":
                self.handle.do_query()
            elif item == "2":
                self.handle.do_hist()
            elif item == "3":
                break
            else:
                print("请输入正确选项")

    def main(self):
        self.__menu_1()


if __name__ == '__main__':
    dict_view = DictView("127.0.0.1", 1314)
    dict_view.main()
